package com.peng.crm.settings.controller;

import com.peng.crm.commons.utils.DateUtil;
import com.peng.crm.commons.utils.MD5Util;
import com.peng.crm.commons.utils.Result;
import com.peng.crm.settings.entity.User;
import com.peng.crm.settings.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/auth")
public class LoginController {
    @Autowired
    private UserService userService;

    /**
     *
     * @param username  登陆账户
     * @param password  登陆密码
     * @return
     */
    @PostMapping("/loginUserAndPassword")
    public Result loginUserAndPassword(@RequestParam("username") String username,
                                       @RequestParam("password") String password,
                                       HttpSession session){
        System.out.println("ssssssssssssssss");
        //根据用户提交账户查询用户是否存在
        User loginUser = userService.findByLoginAct(username);
        if (loginUser == null){
            return Result.error(-2,"用户名不存在");
        }
        //验证密码
        if (!loginUser.getLoginPwd().equals(MD5Util.getMD5(password))){
            return Result.error(-1,"登陆密码有误");
        }
        //验证状态
        if ("0".equals(loginUser.getLockState())){
            return Result.error(-4,"登陆账户已被锁定，请联系系统管理员");
        }
        //验证有效时间
        String expireTime = loginUser.getExpireTime();
        if (StringUtils.hasLength(expireTime) && new Date().compareTo(DateUtil.formatString(expireTime)) > 0){
            return Result.error(-5,"当前账号已失效，请联系系统管理员");
        }
        //当一切判断都通过，表示登陆成功
        session.setAttribute("loginUser",loginUser);
        return Result.success(loginUser);
    }

    /**
     * 登出
     *
     * @param session
     * @return
     */
    @GetMapping("/logout")
    public Result logout(HttpSession session){
        //清除session对象
        session.removeAttribute("loginUser");
        //注销session
        session.invalidate();
        return Result.success();
    }


}
